import React, { useEffect, useState } from 'react';
import { Button, Modal, Form, Select } from 'antd';
import { useForm } from '@formily/react';
import { getModelList, getModelInfo } from '../services';
import { toJS } from '@formily/reactive';
import { TextWidget, getMessage } from '@inbiz/react';

type IProps = {
  value: any;
  onChange: (value: object) => void;
};

const childrenSave = (props: IProps) => {
  // 是否显示modal
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  // 模型列表
  const [modelList, $modelList] = useState<any[]>([]);
  // 当前选中modelKey
  const [activeModelKey, $activeModelKey] = useState<string>('');
  // 当前model字段列表
  const [filedList, $filedList] = useState<any[]>([]);

  const [form] = Form.useForm();
  // formily
  const outerForm: { appInfo?: { appId: string }; fields?: any } = useForm();

  // 获取模型列表
  useEffect(() => {
    let value = toJS(props.value);
    if (value) {
      $activeModelKey(value.model);
      form.setFieldsValue(value);
    }
    getModelList(outerForm.appInfo?.appId || '').then((res) => {
      if (Array.isArray(res.List) && res.List.length) {
        $modelList(res.List);
      }
    });
  }, []);

  // 获取当前模型字段列表
  useEffect(() => {
    if (activeModelKey && activeModelKey !== '') {
      getModelInfo(outerForm.appInfo?.appId || '', activeModelKey).then((res) => {
        if (Array.isArray(res) && res.length) {
          let list = res[0].Fields;
          if (Array.isArray(list) && list.length) {
            $filedList(list);
          }
        }
      });
    }
  }, [activeModelKey]);

  // 显示modal
  const showModal = () => {
    setIsModalVisible(true);
  };

  // 确定
  const handleOk = () => {
    form.validateFields().then((res) => {
      handleCancel();
      props.onChange && props.onChange(res);
    });
  };

  // 取消
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div>
      <Button type="primary" onClick={showModal}>
        <TextWidget>EformDynamicList.configure</TextWidget>
      </Button>
      <Modal
        width={500}
        title={getMessage('EformDynamicList.storageConfiguration')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={getMessage('global.sure')}
        cancelText={getMessage('EformDynamicList.cancel')}
        destroyOnClose
        isMove
      >
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }}>
          <Form.Item
            name="model"
            label={getMessage('EformDynamicList.model')}
            rules={[
              {
                required: true,
                message: `${getMessage('EformDynamicList.model')}${getMessage(
                  'EformDynamicList.tips.cannotBeEmpty',
                )}`,
              },
            ]}
          >
            <Select onChange={(e) => $activeModelKey(e)}>
              {modelList.map((item) => {
                return (
                  <Select.Option value={item.ModelKey} key={item.ModelKey}>
                    {item.Name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            name="refid"
            label="Refid"
            rules={[
              {
                required: true,
                message: `Refid${getMessage('EformDynamicList.tips.cannotBeEmpty')}`,
              },
            ]}
          >
            <Select>
              {filedList.map((item) => {
                return (
                  <Select.Option value={item.Name} key={item.Key}>
                    {item.Name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            name="id"
            label="id"
            rules={[
              {
                required: true,
                message: `id${getMessage('EformDynamicList.tips.cannotBeEmpty')}`,
              },
            ]}
          >
            <Select>
              {filedList.map((item) => {
                return (
                  <Select.Option value={item.Name} key={item.Key}>
                    {item.Name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default childrenSave;
